package com.ruoyi.framework.shiro.web;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StreamUtils;

public class ShiroUserFilter extends UserFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        System.out.println((httpRequest.getHeader("accept")+"5555555"));
        if (this.isLoginRequest(request, response)) {
            return true;
        } else {
            Subject subject = this.getSubject(request, response);
            return subject.getPrincipal() != null;
        }
    }
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);

        if (subject.getPrincipal() == null) {
            // 未认证的用户
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            String s = StreamUtils.copyToString(httpServletRequest.getInputStream(), Charset.defaultCharset());
            System.out.println(httpServletRequest.getHeader("accept")+"3333333333333");

            if (ServletUtils.isAjaxRequest(httpServletRequest)) {
                httpServletResponse.setContentType("application/json; charset=utf-8");

                Map<String, Object> response1 = new HashMap<String, Object>();
                response1.put("code", 401);
                response1.put("msg", "未登录或者登录已失效");

                String json = JSON.toJSONString(response1);

                httpServletResponse.getWriter().write(json);
            } else {
                // 非AJAX请求
                System.out.println(httpServletRequest.getHeader("accept")+"66666666");
                WebUtils.issueRedirect(request, response, getLoginUrl(),null,true,false);
            }

            return false;
        }

        // 用户已认证，但没有相应的权限
        return true;
    }

}

